package cn.hywx.convert.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
/**
 * dbcp数据源单例
 * @author all3n
 *
 */
public class DbcpDataSource {
	private BasicDataSource dataSource = null;
	private static DbcpDataSource _instance = null;
	
	private DbcpDataSource(){
		this.init();
	}
	
	public void init() {
		if (dataSource != null) {
			try {
				dataSource.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			dataSource = null;
		}

		try {
			Properties dbProps = new Properties();
			InputStream inStream = DbcpDataSource.class.getResourceAsStream("/dbcp.properties");
			try {
				dbProps.load(inStream);
			} catch (IOException e) {
				System.out.println("load properties error!");
				System.exit(0);
			}
			dataSource = (BasicDataSource) BasicDataSourceFactory
					.createDataSource(dbProps);
		} catch (Exception e) {
			System.out.println("data source init error!\n"+e.getMessage());
			System.exit(0);
		}
	}
	
	public static DbcpDataSource getInstance(){
		if(_instance == null){
			_instance = new DbcpDataSource();
		}
		return _instance;
	}
	
	public BasicDataSource getDataSource(){
		return dataSource;
	}
	
	public void test(){
		QueryRunner runner = new QueryRunner(dataSource);
		String sql = "select * from document";
		Object [] param = new Object[]{};
		ResultSetHandler<List<Map<String, Object>>> rsh = new MapListHandler();
		try {
			List<Map<String,Object>> list = runner.query(sql, param, rsh);
			for(Map<String,Object> m:list){
				System.out.println("id:"+m.get("id"));
			}
			System.out.println(list);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		DbcpDataSource du = new DbcpDataSource();
		
		du.test();
	}
}
